package com.aaa.security;

import com.aaa.entity.ResponseMsg;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
* 未认证：用户没有登录,访问资源
* */
@Component
public class EntryPointHandler implements AuthenticationEntryPoint {



    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // Emp principal = (Emp) authentication.getPrincipal();
        //响应设置
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-type","application/json");
        httpServletResponse.setStatus(500);
        ResponseMsg responseMsg=new ResponseMsg(503,"未认证",e.getMessage());

        //FastJSPN
        //写:字符输出流
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSONObject.toJSONString(responseMsg));
        writer.flush();
        writer.close();
    }
}
